package com.home.coroutines

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {
    val TAG = "zzm debug"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        GlobalScope.launch(Dispatchers.Main) {
            val res1 = async { io4() }
            val res2 = async { io5() }
            val data = res1.await() + res2.await()
            ui4(data)
        }
    }

    private suspend fun io4() = withContext(
        Dispatchers.IO
    ) {
        delay(2000)
        Log.d(TAG, "io method,thread:${Thread.currentThread().name}")
        1
    }

    private suspend fun io5() = withContext(
        Dispatchers.IO
    ) {
        delay(3000)
        Log.d(TAG, "io method,thread:${Thread.currentThread().name}")
        2
    }

    private fun ui4(value: Int) {
        Log.d(TAG, "ui method,thread:${Thread.currentThread().name},result:${value}")
    }
}